/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.dpi.users.group.adsl;

import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiusergroup;
import cn.net.greenet.db.bean.UgUsername;
import com.ambimmort.umessage.UcType;
import com.ambimmort.umessage.uc.outgoing.vm.x40;
import com.ambimmort.umessage.util.HexUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Administrator
 */
@WebServlet(name = "cn.net.greenet.dpi.users.group.adsl.servlet.Create", urlPatterns = {"/dpium/group/adsl/create"})
public class Create extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String json = request.getParameter("json");
        JSONObject jsonObj = JSONObject.fromObject(json);
        String groupId = jsonObj.getString("groupId");
        JSONArray usernames = jsonObj.getJSONArray("usernames");
        PrintWriter out = response.getWriter();
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        Dpiusergroup bean = (Dpiusergroup) session.get(Dpiusergroup.class, Integer.parseInt(groupId));
        Transaction tx = session.beginTransaction();
        try {
            for (int i = 0; i < usernames.size(); i++) {
                UgUsername uu = new UgUsername(bean);
                uu.setName(usernames.getString(i));
                session.saveOrUpdate(uu);
            }
            tx.commit();

            java.util.List<x40> msgs = new ArrayList<x40>();

            x40.User user = null;
            x40 msg = null;
            for (int i = 0; i < usernames.size(); i++) {
                if ((i) % 2000 == 0) {
                    msg = new x40();
                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte)0x40}));
                    msg.setAction(UcType.newUINT1(1));
                    msg.setUserGroupName(UcType.newUString_UINT1(bean.getName()));
                    msg.setUserGroupNo(UcType.newUINT2(bean.getId()));
                    msg.setMessageSerialNo(UcType.newUINT4(0));
                    msgs.add(msg);
                }
                user = new x40.User();
                user.setUserName(UcType.newUString_UINT1(usernames.getString(i)));
                user.setUserType(UcType.newUINT1(1));
                msg.getUserNum().add(user);
            }

            
            // TODO: change the print method to PolicySupport invocation
            for (x40 m : msgs) {
                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
                System.out.println(HexUtil.getHex(m.toBytes()));
                String comment = "【"+bean.getId()+"("+bean.getName()+")"+"】【user】【＋】【"+usernames.size()+"】";
                System.out.println(comment);
                PolicySupport.getInstance().getApi().addPolicy("0x40", bean.getInstanceName(), m.toJSON(), comment);
            }

            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"result\":\"false\"}");
            tx.rollback();
        } finally {
            out.close();
            session.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
